package com.onjob.recruit;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import util.dao.HibernateDaoImpl;

import com.onjob.security.Users;

public class CompanyDaoImpl extends HibernateDaoImpl<Company, String> implements
		CompanyDao {
	public Company getCompanyByUser(Users user) {
		Company company = (Company)this.getHibernateTemplate().find(
				"from " + Company.class.getName() + " c where c.userId.id="
						+ user.getId()).get(0);
		return company;
	}

	public void deleteCompanyFindByUser(final Long userId) {
		StringBuffer hql = new StringBuffer();
		hql.append("delete from Company c where 1=1 ");
		hql.append("and c.userId.id=:userId ");
		final String sss = new String(hql);
		this.getHibernateTemplate().execute(
		new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(sss);
				query.setLong("userId", userId);
				query.executeUpdate();
				return null;
			}
			
		});
	}
	public boolean companyNameIsExist(final String companyName){
		StringBuffer hql = new StringBuffer();
		hql.append("from Company c where 1=1 ");
		hql.append("and c.companyName=:companyName ");
		final String s = new String(hql);
		return (Boolean)this.getHibernateTemplate().execute(
				new HibernateCallback(){
					@SuppressWarnings("unchecked")
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query=session.createQuery(s);
						query.setString("companyName", companyName);
						List<Company> list = (List<Company>) query.list();
						if(list.size()!=0){
							return true;
						}else{
							return false;
						}
					}
					
				}
		);
	}
}
